﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;

namespace WeiXinSDK.DataModel
{
    public class ButtonJSConverter : JavaScriptConverter
    {
        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            Button button = new Button();

            object value = null;
            if (dictionary.TryGetValue("name", out value))
                button.name = (string)value;
            if (dictionary.TryGetValue("type", out value))
                button.type = (string)value;
            if (dictionary.TryGetValue("key", out value))
                button.key = (string)value;
            if (dictionary.TryGetValue("url", out value))
                button.url = (string)value;
            if (dictionary.TryGetValue("sub_button", out value))
            {
                if (value != null && value.GetType() == typeof(ArrayList))
                {
                    var list = (ArrayList)value;
                    button.sub_button = new List<Button>();

                    foreach (Dictionary<string, object> item in list)
                    {
                        button.sub_button.Add((Button)this.Deserialize(item, type, serializer));
                    }
                }
                else
                {
                    button.sub_button = null;
                }
            }
            return button;
        }

        public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            var node = obj as Button;
            if (node == null)
                return null;
            if (!string.IsNullOrEmpty(node.type))
                dic.Add("type", node.type);
            if (!string.IsNullOrEmpty(node.name))
                dic.Add("name", node.name);
            if (!string.IsNullOrEmpty(node.key))
                dic.Add("key", node.key);
            if (!string.IsNullOrEmpty(node.url))
                dic.Add("url", node.url);
            if (node.sub_button != null)
                dic.Add("sub_button", node.sub_button);

            return dic;
        }

        public override IEnumerable<Type> SupportedTypes
        {
            get
            {
                return new Type[] { typeof(Button) };
            }
        }
    }
}
